<?php
require_once 'config.php';

try {
	$db = new PDO('pgsql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
	print "Error!: " . $e->getMessage();
	die();
}
$result = '';
if (isset($_GET['token'])) {

	$token = $_GET['token'];
	$sql = sprintf('SELECT "ID" FROM "users" WHERE "TOKEN" LIKE \'%s\' AND "EXPIRATION" > CURRENT_TIMESTAMP', $token);
	$stmt = $db->query($sql)->fetch();
	$result = $stmt;
	
	if (isset($stmt['ID'])) {
		$sql = 'SELECT "ID","TITLE","CONTENT","DT","ID_USER" FROM "NEWS"';
		$stmt = $db->query($sql);
		$result = '{"news":[';
		while ($row = $stmt->fetch()) {
			$result .= sprintf('{"id":%d,"title":"%s","content":"%s","date":"%s","id_user":%d},',$row['ID'],$row['TITLE'],$row['CONTENT'],$row['DT'],$row['ID_USER']);
		}
		$result = rtrim($result, ",");
		$result .= ']}';
	}
		else {
		$result = '{"error": "не действительный/неверный токе"}';
	}
	
}
else {
	$result = '{"error": "не передан токен"}';
}
echo $result;

?>
